import homeStore from "../../store/home_store"
import {
  throttle
} from 'underscore'

Page({
  data: {
    active: 0,
    category_id: 0,
    page: 1,
    tabs: ['全部服务', '在提供', '正在找'],
    categoryList: [],
    serviceList: []
  },

  onLoad() {
    // 发起action
    homeStore.dispatch("fetchCategoryAction")
    homeStore.dispatch('fetchServiceListAction', this.data.page, this.data.active, this.data.category_id)
    // 监听
    homeStore.onState('classifyLists', this.handleCategoryList)
    homeStore.onState('serviceList', this.handleServiceList)
  },

  // 更新数据方法
  handleCategoryList(value) {
    this.setData({
      categoryList: value
    })
  },
  handleServiceList(value) {
    this.setData({
      serviceList: value
    })
  },

  // 卸载方法
  onUnload() {
    homeStore.offState('classifyLists', this.handleCategoryList)
    homeStore.offState('serviceList', this.handleServiceList)
  },

  // tabs点击事件
  onChange: throttle(function (event) {
    const selectIndex = event.detail.index
    // 初始化page数据
    this.setData({
      page: 1,
      category_id: 0
    })
    this.setData({
      active: selectIndex
    })
    homeStore.dispatch('fetchServiceListAction', this.data.page, this.data.active, this.data.category_id, 'empty')
    this.handleScrollToTop()
  }, 500),
  // 分类：子组件点击事件
  handleClassify: throttle(function(event) {
    const cateId = event.detail
    // 初始化page数据
    this.setData({
      page: 1
    })
    this.setData({
      category_id: cateId
    })
    homeStore.dispatch('fetchServiceListAction', this.data.page, this.data.active, this.data.category_id, 'empty')
  }, 500),

  // 下拉刷新事件 
  onPullDownRefresh() {
    homeStore.dispatch("fetchCategoryAction")
    homeStore.dispatch('fetchServiceListAction', this.data.page, this.data.active, this.data.category_id, 'empty')
    wx.stopPullDownRefresh()
  },

  // 触底加载数据
  onReachBottom() {
    console.log('触底啦');
    ++this.data.page
    homeStore.dispatch('fetchServiceListAction', this.data.page, this.data.active, this.data.category_id)
  },

  // 切换页面置顶的方法
  handleScrollToTop() {
    wx.pageScrollTo({
      scrollTop: 0
    })
  }
})